#!/usr/bin/env python

import sys
import os
from os.path import join
import cherrypy
import sqlalchemy
import Cheetah
import webbrowser
import thread

#print 'using cherrypy', cherrypy.__version__
#print 'using sqlalchemy', sqlalchemy.__version__
#print 'using cheetah', Cheetah.Version

if __name__ == '__main__':
    
    #set the path for the application's imports
    originalPath = os.getcwd()
    path = sys.path[0]
    print path
    os.chdir( path )
    print os.getcwd()
    sys.path.append(path)
    
    from dailyspents.view.MainView import MainView
    from dailyspents.view.LoginView import LoginView
    from dailyspents.view.SpentView import SpentView
    from dailyspents.view.UserView import UserView
    from dailyspents.model import orm
    
    #create database tables
    try:
        orm.createTables()
    except sqlalchemy.exceptions.DBAPIError, e:
        print 'ERROR: Could not connect to your database.'
        raise e
        sys.exit(1)

    staticContentDir = join(os.getcwd(), '..', 'web')
    
    configMap = {'global' : {'sessionFilter.on':True,
                             'server.environment' : 'production'},
                 '/static' : {'static_filter.on':True,
                              'static_filter.dir':staticContentDir},
                 'error_page.404': "../web/html/404.html"
                 }
    
    #starts the server according to configMap dict
    cherrypy.config.update(updateMap = configMap)
    cherrypy.root = LoginView()
    cherrypy.root.main = MainView()
    cherrypy.root.spent = SpentView()
    cherrypy.root.user = UserView()
    
    #thread.start_new_thread(cherrypy.server.start, ())
    cherrypy.server.start()
    #while not cherrypy.server.ready:
    #    pass
    
    #webbrowser.open('http://localhost:8080/')
    
    #returns to original folder
    os.chdir(originalPath)
